#!/bin/sh
# 备份MySQL数据库
# 基于Xtrabackup程序
# 修改FullHour数值可以更改完全备份时钟(24小时制，默认凌晨零点)
# 或者在本脚本名后增加参数full也可实现完全备份
# 其它时间增量备份
MySQLDir=/App/mysql
MyCnf=/etc/my.cnf
XtrabackupDir=/App/xtrabackup
export PATH="/sbin:/bin:/usr/sbin:/usr/bin:$MySQLDir/bin:$XtrabackupDir/bin"

User=root
Password=root
MailTo=dongsong@aifan.com
Day=$(date +%Y-%m-%d)
Hour=$(date +%H)
SaveDays=30
FullHour=00
BackupRoot=/data/backup
BaseDir=$BackupRoot/$Day/full
IncDir=$BackupRoot/$Day/$Hour
MailFile=$BackupRoot/$Day/mail
HostName=$(hostname)
IPList=$(ifconfig | grep -v '127.0.0.1' | sed 's/addr://g' | grep 'inet ' | awk '{print $2}')

find $BackupRoot -maxdepth 1 -type d -mtime +$SaveDays -exec rm -rf {} \;
test -d $BackupRoot/$Day || mkdir -p $BackupRoot/$Day

cat > $MailFile << EOF
$HostName
$IPList
EOF

if [ "$Hour" == "$FullHour" -o "$1" == "full" ]; then
	LogFile=$BackupRoot/$Day/full.log
	innobackupex --defaults-file=$MyCnf --no-timestamp --user $User --password $Password $BaseDir 2>> $LogFile
else
	LogFile=$BackupRoot/$Day/inc$Hour.log
	innobackupex --defaults-file=$MyCnf --no-timestamp --user $User --password $Password --incremental --incremental-basedir=$BaseDir $IncDir 2>> $LogFile
fi

test "$?" -ne 0 && cat $MailFile $LogFile | mutt -s "MySQL backup failed" $MailTo
